import React, { Component } from 'react';
import { toJS } from 'mobx';
import { observer, inject } from "mobx-react";
import { Popover, Spin, Progress, message } from 'antd';
import moment from 'moment';
import cass from 'classnames';
import styles from './index.module.less';
import IF from '../../components/If';
import Chat from '../chat';
import Task from '../task';
import Project from '../project';
import Contact from '../contact';
import config from '../../config';
import BottomMenu from './bottomMenu';
import UnlinkModal from '../../components/UnlinkModal';
import Avatar from '../../components/Avatar';
import logo from '../../assets/u6.png';

import logout from '../../utils/logout';
import sdk from '../../utils/imSdk';

// 定义左边栏按钮
const leftItems = [
    { icon: 'chat' },
    { icon: 'widgets' },
    { icon: 'tune' },
    { icon: 'contacts' },
    { icon: 'phone' },
    { icon: 'autorenew' }
];

const items = [
    { label: '公司', key: 'company' },
    { label: '所在地', key: 'address' },
    { label: '个性签名', key: 'signature' },
];

const listenersMap = {
    0: 'chatListListener',
    1: 'projectListListener',
    2: 'taskListListener'
}

@inject(
    ({
        commonState, userState, chatState, contactsState, taskState, projectState
    }) => ({
        commonState, userState, chatState, contactsState, taskState, projectState
    })
)
@observer
class Dashboard extends Component {

    state = {
        loading: false,
        activeIndex: 0,
        online: true,
    }

    componentWillMount() {
        this.initRegularNotification();
        setInterval(this.initRegularNotification, 60 * 1000);

        const { ipcRenderer } = window.electron;
        // 监听F12 Open the DevTools
        document.addEventListener('keyup', e => {
            if (e.keyCode === 123) {
                ipcRenderer.send('openDevTools');
            }
        })

        // 获取当前用户信息
        this.props.userState.getUserInfo();
        // 获取当前用户的通信录
        this.props.contactsState.getList();

        // 获取创建任务需要的基础选项数据
        const { getDetailSelectList, getLinkProjectList, getAlarmTaskList } = this.props.taskState;
        getLinkProjectList();
        getAlarmTaskList();
        getDetailSelectList();

        // 初始化腾讯云聊天平台
        sdk.init(this.initSuccess, this.initError, {
            onChatListChange: this.onChatListChange,
            onChatMsgsChange: this.onChatMsgsChange,
            onChatOtherMsgsChange: this.onChatOtherMsgsChange,
            onNewMsgByOneToUpdate: this.onNewMsgByOneToUpdate,
            onChatImSdkError: this.onChatImSdkError,
            onKickedToClearChatInstance: this.onKickedToClearChatInstance,
        }, {
            "onGroupInfoChangeNotify": this.onGroupInfoChangeNotify, // 监听群资料变化事件，选填
            "onKickedEventCall": this.onKickedEventCall, // 被其他登录实例踢下线
        });




        // 订阅对于主线程的事件监听, 用于模块之间的跳转
        ipcRenderer.on('web-goPage', this.goPage);

        // 订阅对于主线程的事件监听, 修改当前组件state的值，触发全局loading/或者更新progress
        ipcRenderer.on('set-dashboard-state', (event, data) => {
            this.setState(data);
        });

        // 订阅对于主线程的事件监听
        ipcRenderer.on('download-callback', (event, data) => {
            message[['error', 'success'][data.success]](data.msg);
        });

        // 订阅对于主线程的事件监听
        ipcRenderer.on('open-item-callback', (event, data) => {
            window.isOpenPreviewItem = false;
            message[['error', 'success'][data.success]](data.msg);
        });

        // 订阅对于主线程的事件监听，监听聊天内容右键菜单触发的事件
        ipcRenderer.on('on-chat-msg-dispatch', (event, data) => {
            const { type, textValue, GroupId, MsgSeq } = data;
            if (type === 'settask') {
                // 弹起创建任务弹框
                const { commonState: { onCreateTaskModalChange } } = this.props;
                onCreateTaskModalChange({
                    taskModal: true,
                    baseData: { content: textValue }
                });
            } else if (type === 'withdraw') {
                const requestData = {
                    GroupId,
                    MsgSeqList: [{ MsgSeq }]
                }
                console.log('--withdraw--', requestData);
                // 撤回功能需要后端配合，暂时做不了
            }
        });

        // 订阅对于主线程的resume事件监听
        ipcRenderer.on('on-resume', () => {
            const { online } = this.state;
            if (!online) return; // online离线的时候由sdk内部检查刷新
            const { setChatContent, chatId } = this.props.chatState;
            sdk.recentContact();
            if (chatId) {
                setChatContent(chatId, []);
                sdk.createChatInstance(undefined, chatId);
            }
        });

        // 订阅对于主线程的事件监听
        ipcRenderer.on('on-get-new-message', (event) => {
            const { chatState: { totalMsgCount, chatList } } = this.props;
            const newChatList = toJS(chatList).reduce((pre, c) => {
                let groups;
                if (c.groups && c.groups.length) {
                    groups = c.groups.filter(g => g.SessionItem && g.SessionItem.UnreadMsgCount);
                }
                if (groups && groups.length) return [...pre, { ...c, groups }]
                else return pre;
            }, []);
            // 最多显示五个，默认高度 28和57 字段太长的滚动
            const height = newChatList.slice(0, 5).reduce((pre, c) => {
                const gh = 57 * c.groups.length;
                return pre + gh + 28;
            }, 88);
            event.sender.send('on-accept-new-message', { totalMsgCount, chatList: newChatList, height });
        });

        ipcRenderer.on('debug-msg', (event, msg) => {
            console.log(msg);
        })
    }

    initSuccess = () => {
        console.log('----init success----');
    }

    initError = (err) => {
        console.log('----init err----', err);
    }

    onChatListChange = (recentSessMap, needUpdate) => {
        // console.log('----recentSessMap----', recentSessMap);
        const { chatState: { getList } } = this.props;
        getList({}, recentSessMap, needUpdate);
    }

    onChatMsgsChange = (chatId, msgs) => {
        const { chatContent, setChatContent } = this.props.chatState;
        // console.log('----onChatMsgsChange----', chatId, msgs);
        const list = [...(chatContent[chatId] || []), ...msgs];
        setChatContent(chatId, list);
        this.flashIcon();
    }

    onChatOtherMsgsChange = (chatId, msgs) => {
        this.flashIcon();
    }

    // 只有fromAccount为1才会触发 详情信息同步
    onNewMsgByOneToUpdate = (msgData, groupId) => {
        // console.log('--onNewMsgByOneToUpdate--', msgData, groupId)
        const { data } = msgData;
        if (!data) return;
        const { type, stagestatus, projectid, taskid } = data;
        const isTask = type === 1;
        const isProject = type === 0;
        const isFinish = stagestatus === 2;
        const isRestart = stagestatus === 1;

        const { activeIndex } = this.state;
        const { chatState, projectState, taskState } = this.props;
        if (activeIndex === 0 && (projectid || taskid)) {
            const { chatListCurrentItem } = chatState;
            // 是当前显示的详情
            if (chatListCurrentItem && chatListCurrentItem.group && chatListCurrentItem.group.groupid === groupId) {
                if (isFinish || isRestart) {
                    chatListCurrentItem.group.iscomplete = !!isFinish;
                    chatListCurrentItem.group.isavtive = !isFinish;
                    const ev = new CustomEvent(listenersMap[activeIndex], {
                        bubbles: 'true',
                        cancelable: 'true',
                        detail: { activeStatus: isFinish ? 1 : 0 }
                    });
                    document.dispatchEvent(ev);
                }
                if (isTask) {
                    taskState.getDetail({ taskid })
                }
            }
        } else if (activeIndex === 1 && isProject && projectid) {
            projectState.getList();
        } else if (activeIndex === 2 && isTask && taskid) {
            // 如果显示的是任务详情页面
            const { detailData } = taskState;
            taskState.getList({ searchkey: '' });
            // 是当前显示的详情
            if (detailData && detailData.info && detailData.info.recid && detailData.info.recid === taskid) {
                // 变更列表状态
                if (isFinish || isRestart) {
                    const ev = new CustomEvent(listenersMap[activeIndex], {
                        bubbles: 'true',
                        cancelable: 'true',
                        detail: { activeStatus: isFinish ? 1 : 0 }
                    });
                    document.dispatchEvent(ev);
                }
                // 刷新详情
                taskState.getDetail({ taskid });
                // 更新侧边栏
                if (projectid) {
                    projectState.getDetail({ projectid });
                    if (taskState.detailDataForSide) {
                        taskState.getDetailForSide({ taskid });
                    }
                }
            }
        }
    }

    onChatImSdkError = (err) => {
        console.log('---onChatImSdkError---', err);
        if (err && err.ErrorCode && err.ErrorCode === -2) {
            message.error('网络异常，请检查网络');
        } else if (err && err.ErrorCode === -99999) {
            this.setState({
                online: false,
                bannerTips: { type: 'error', message: '当前网络不可用，请检查你的网络设置！' }
            });
        } else if (err && err.ErrorCode === 99999) {
            message.success(err.message);
            this.setState({ online: true, bannerTips: undefined }, this.initRegularNotification);
        } else {
            message.error(`imSdk err: ${err.message}` || 'imSdk err');
        }
    }

    // 被移出群聊
    onKickedToClearChatInstance = () => {
        this.pageChange(0)();
    }

    onGroupInfoChangeNotify = () => {
        console.log('----onGroupInfoChangeNotify----');
    }

    onKickedEventCall = () => {
        console.log('----onKickedEventCall----');
        message.error('您的帐号于另一台电脑上登录', 2, logout);
    }

    // 通知主线程闪烁任务栏logo
    flashIcon = () => {
        const { ipcRenderer } = window.electron;
        ipcRenderer.send("window-new-msg");
    }

    // 页面切换重置详情数据
    resetStateDetailData = () => {
        const { commonState, contactsState, taskState, projectState, chatState } = this.props;
        commonState.setStateValue('sideOpen', false);
        projectState.setStateValue('detailData', undefined);
        taskState.setStateValue('detailData', undefined);
        contactsState.setStateValue('detailData', {});
        chatState.setStateValue('chatId', null);
        chatState.setStateValue('chatListCurrentItem', undefined);
    }

    pageChange = (i) => () => {
        if (i === 4) return;
        if (i === 5) {
            window.location.reload();
            return;
        }
        this.resetStateDetailData();
        // 点击跳转则设置activeIndex，并且把其它数据设置为默认值
        this.setState({
            activeIndex: i,
            chatgroupid: undefined,
            projectid: undefined,
            taskid: undefined,
            contactid: undefined,
        });
    }

    goPage = (event, { index, data }) => {
        // console.log('--goPage--', data);
        this.resetStateDetailData();
        if (index === 0) { // 跳转聊天页面
            const { chatgroupid } = data;
            this.setState({ activeIndex: index, chatgroupid });
        } else if (index === 1) { // 跳转项目详情
            const { recid: projectid } = data;
            this.setState({ activeIndex: index, projectid });
        } else if (index === 2) { // 跳转任务详情
            const { taskid } = data;
            this.setState({ activeIndex: index, taskid });
        } else if (index === 3) { // 跳转联系人详情
            const { recid: contactid } = data;
            this.setState({ activeIndex: index, contactid });
        }
    }

    renderHeader = (info) => {
        return (
            <div className={styles.popoverHeader}>
                {info.realname}
                {
                    info.gender ?
                        <span className={cass('mdi mdi-gender-female', styles.female)} /> :
                        <span className={cass('mdi mdi-gender-male', styles.male)} />
                }
                <div className={styles.subt}>帐号：{info.username}</div>
            </div>
        )
    }

    renderContent = (info) => {
        return (
            <div className={styles.popoverContent}>
                {items.map(v => (
                    <div className={styles.item} key={v.key}>
                        <div className={styles.left}>{v.label}</div>
                        <div className={styles.right}>{v.render ? v.render(info[v.key]) : (info[v.key] || '')}</div>
                    </div>
                ))}
            </div>
        )
    }

    renderCallContent = () => {
        return (
            <div className={styles.callContent}>
                <img src={logo} alt="logo" />
                <div>使用过程中如遇疑问</div>
                <div>请拨打：13580589317</div>
            </div>
        )
    }

    // 定时做16点的工作提醒
    initRegularNotification = () => {
        const { bannerTips } = this.state;
        const day = moment().day();
        if (bannerTips && bannerTips.type === 'error') {
            return;
        }
        if (day === 0 || day === 6) {
            if (bannerTips && bannerTips.type === 'warning') this.setState({ bannerTips: undefined })
            return;
        }
        const start = moment(`${moment().format('YYYY-MM-DD')} 16:00:00`).format('X');
        const end = moment(`${moment().format('YYYY-MM-DD')} 18:00:00`).format('X');
        const current = new Date().getTime() / 1000;
        if (current >= start && current <= end && !bannerTips) {
            this.setState({
                bannerTips: {
                    type: 'warning',
                    message: '快下班咯，请尽快处理今日工作！',
                    tips: '1.回复各方问题（汇报目前工作进展和下一步工作计划) 2.安排各方需要协助的工作（明确时间、地点、人物、内容 3.每个待完成的工作设置任务提醒 4.扫描、上传取得的案件资料 5.已完成的任务点击完成，未完成的任务调整任务开始时间'
                }
            })
        }
        if ((current < start || current > end) && bannerTips) {
            this.setState({ bannerTips: undefined })
        }
        // console.log(start, current, end)
    }

    render() {

        let loaded = this.props.userState.loaded && this.props.contactsState.loaded
            && this.props.taskState.loaded.project && this.props.taskState.loaded.task && this.props.taskState.loaded.detailSelect;
        if(loaded){
            this.props.commonState.setStatus('login');
            message.success('已连接.')
        }

        const {
            loading, online, loadingText, loadingPercent = 0, showloadingProgress, bannerTips,
            activeIndex, chatgroupid, projectid, taskid, contactid
        } = this.state;
        const { chatState: { totalMsgCount }, userState: { info } } = this.props;
        return (
            <Spin
                wrapperClassName={styles.loadingContent}
                spinning={loading}
                tip={(
                    <div className={styles.wraploadingText}>
                        {loadingText || 'Loading...'}
                        {showloadingProgress && <Progress percent={Number(loadingPercent)} status="active" />}
                    </div>
                )}
            >
                <div className={styles.App}>
                    <div className={styles.leftBar}>
                        <div className={styles.wrapAvatar}>
                            <Popover
                                placement="rightTop"
                                title={this.renderHeader(info)}
                                content={this.renderContent(info)}
                                trigger="click"
                            >
                                <span className={styles.avatarBtn} />
                            </Popover>
                            <Avatar
                                headimage={info.headimage}
                                username={info.realname}
                                color={!info.headimage && 'mainColor'}
                                borderColor={!info.headimage && 'mainBorderColor'}
                            />
                        </div>
                        {
                            leftItems.map((v, i) => (
                                <div
                                    key={v.icon}
                                    className={cass(styles.wrapItem, { [styles.active]: activeIndex === i })}
                                    onClick={this.pageChange(i)}
                                >
                                    {i === 4 ? (
                                        <Popover
                                            placement="rightTop"
                                            content={this.renderCallContent()}
                                            trigger="click"
                                        >
                                            <div className={styles.wrapCall}>
                                                <span className={`mdi mdi-${v.icon}`} />
                                            </div>
                                        </Popover>
                                    ) : <span className={`mdi mdi-${v.icon}`} />}
                                    {
                                        i === 0 && totalMsgCount ? (
                                            <div className={styles.count}>
                                                <span className={cass(`mdi mdi-circle`, styles.bg)} />
                                                <span className={styles.num}>{totalMsgCount}</span>
                                            </div>
                                        ) : null
                                    }

                                </div>
                            ))
                        }
                        <div className={styles.name}>{config.name}</div>
                        <BottomMenu activeIndex={activeIndex} />
                        <UnlinkModal show={!online} onClose={() => this.setState({ online: true })} />
                    </div>
                    <div className={styles.rightContent}>
                        <IF condition={activeIndex === 0}><Chat bannerTips={bannerTips} chatgroupid={chatgroupid} /></IF>
                        <IF condition={activeIndex === 1}><Project bannerTips={bannerTips} projectid={projectid} /></IF>
                        <IF condition={activeIndex === 2}><Task bannerTips={bannerTips} taskid={taskid} /></IF>
                        <IF condition={activeIndex === 3}><Contact bannerTips={bannerTips} contactid={contactid} /></IF>
                    </div>
                </div>
            </Spin>
        );
    }
}

export default Dashboard
